﻿/***
 * 
 *    Title: "ZGUIFW"UI框架项目
 *           主题： 消息传递中心      
 *    Description: 
 *           功能： 负责所有UI界面之间的消息传递
 *    Date: 2018
 *    Version: 0.1版本
 */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ZGUIFW
{
	public class MessageCenter
	{
		public delegate void DelMessageDelivery(KeyValueMsg msg);
        //消息中心缓存集合
        //string 消息分类
		//DelMessageDelivery 执行的委托
		public static Dictionary<string, DelMessageDelivery> _dicMessage = new Dictionary<string, DelMessageDelivery>();

        /// <summary>
        /// Adds the Msg listener.
        /// </summary>
        /// <param name="msgType">Message type.</param>
        /// <param name="delMessage">Del message.</param>
		public static void AddMsgListener(string msgType, DelMessageDelivery delMessage)
		{
			if (_dicMessage.ContainsKey(msgType) == false)
			{
				_dicMessage.Add(msgType, null);
			}
			_dicMessage[msgType] += delMessage;
		}
        /// <summary>
        /// Removes the message listener.
        /// </summary>
        /// <param name="msgType">Message type.</param>
        /// <param name="delMessage">Del message.</param>
		public static void RemoveMsgListener(string msgType, DelMessageDelivery delMessage)
		{
			if (_dicMessage.ContainsKey(msgType) == false) return;
			if (_dicMessage[msgType] == null) return;
			_dicMessage[msgType] -= delMessage;

		}
        /// <summary>
        /// Removes all message listener.
        /// </summary>
		public static void RemoveAllMsgListener()
		{
			if (_dicMessage == null) return;
			_dicMessage.Clear();
		}
        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="msgType">Message type.</param>
        /// <param name="kv">Kv.</param>
		public static void SendMsg(string msgType, KeyValueMsg kv)
		{
			DelMessageDelivery del;
			if(_dicMessage.TryGetValue(msgType, out del))
			{
				if (del == null) return;
				del(kv);
			}
		}
	}	
	public class KeyValueMsg
	{
		private string _key;
		private object _value;

		public string Key
		{
			get { return _key; }
		}
		public object Value
		{
			get { return _value; }
		}
		public KeyValueMsg(string key, object value)
		{
			_key = key;
			_value = value;
		}
	}
}

